const { merge } = require('webpack-merge');
const common = require('./webpack.common.js');
const net = require('net');

let PORT = 9000;

// const express = require('express');
// const webpack = require('webpack');
// const webpackDevMiddleware = require('webpack-dev-middleware');

const config = merge(common, {
  mode: 'development', // development,production
  devtool: 'inline-source-map',
  devServer: {
    contentBase: './',
    hot: true,
    historyApiFallback: true,
    // port: 3000,
    publicPath: '/',
  },
});

// const app = express();
// const compiler = webpack(config);

// app.use(
//   webpackDevMiddleware(compiler, {
//     publicPath: config.output.publicPath,
//   })
// );

// // Serve the files on port 3000.
// app.listen(4000, function () {
//   console.log('Example app listening on port 3000!\n');
// });

const getPort = () => {
  return new Promise(resolve => {
    const server = new net.Server();
    server.listen(PORT, '127.0.0.1');

    // console.log(server);
    // return;

    function err(err) {
      console.log(`端口${PORT}已被占用，重新切换端口`);
      PORT++;
      resolve(0);
      server.close(); // 关闭服务
    }

    function success() {
      // 执行这块代码说明端口未被占用.abs
      server.removeListener('error', err);
      server.close(); // 关闭服务
      resolve(PORT);
    }

    server.once('listening', success);

    server.once('error', err);
  });
};

const a = async () => {
  const res = await getPort();
  if (res === 0) {
    return a();
  }
  return res;
};

module.exports = a().then(res => {
  config.devServer.port = res;
  return config;
});
